import prompt from '../../utils/prompt.js';
import Api from '../../utils/api.js';
import utils from '../../utils/util.js';

const app = getApp();

// pages/orderDetail/orderDetail.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    refuseDialog: null,
    deliverDialog: null,
    agreeDialog: null, // "同意"弹窗

    originDeliverList: [], // 原始数据
    deliverList: [],
    deliverIndex: -1,
    message: '', // 操作留言
    historyList: [], // 历史状态列表
    userType: '', // 用户类型

    order: {}, // 当前预约对象
    oprType: 'approval' // 操作类型，用于区分审批和详情 approval:审批, detail: 详情
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      oprType: options.oprType,
      userType: app.globalData.userInfo.userType
    }, () => {
      if (this.data.userType === '1') {
        this.getSubManagers();
      }
      const order = app.globalData.orderDetail;
      this.setData({ order }, () => {
        this.getOrderDetail();
      });
      if (options.oprType === 'approval') {
        wx.setNavigationBarTitle({
          title: '审批详情'
        });
      } else {
        let orderType = '';
        switch (order.application_type) {
        case '1': orderType = '用餐申请'; break;
        case '2': orderType = '住宿申请'; break;
        case '3': orderType = '会议预约'; break;
        case '4': orderType = '用车预约'; break;
        case '5': orderType = '物业服务'; break;
        default: break;
        }
        wx.setNavigationBarTitle({
          title: `预约详情-${orderType}`
        });
      }
    });

    const agreeDialog = this.selectComponent('#agree-dialog');
    const deliverDialog = this.selectComponent('#deliver-dialog');
    const refuseDialog = this.selectComponent('#refuse-dialog');
    this.setData({ agreeDialog, deliverDialog, refuseDialog });
  },

  /* --=================数据接口=================-- */
  // 查询订单详情
  async getOrderDetail () {
    const res = await Api.getOrderDetail({
      applicationId: this.data.order.application_id,
      sessionKey: app.globalData.sessionKey
    });
    if (res) {
      res.message.forEach(item => {
        const addDate = utils.formatTime(new Date(item.add_time), 'YYYY-MM-DD hh:mm:ss');
        const addDateArr = addDate.split(' ');
        item.add_date = addDateArr[0];
        item.add_time = addDateArr[1];
        switch (item.approve_ret) {
        case '1': item.ret_text = '发起审批'; break;
        case '2': item.ret_text = '已转发'; break;
        case '3': item.ret_text = '已同意'; break;
        case '4': item.ret_text = '已拒绝'; break;
        case '5': item.ret_text = '审批中'; break;
        default: break;
        }
      });
      this.setData({ historyList: res.message.reverse() });
    }
  },
  // 查询子管理员
  async getSubManagers () {
    const res = await Api.getSubManagers({ sessionKey: app.globalData.sessionKey });
    if (res) {
      this.setData({
        originDeliverList: res.message || [],
        deliverList: res.message.map(er => er.user_name)
      });
    }
  },
  // 撤回申请
  async revokeOrder () {
    const res = await Api.revokeOrder({
      applicationId: this.data.order.application_id,
      sessionKey: app.globalData.sessionKey
    });
    if (res) {
      prompt.showToast('撤回成功', 'success', { mask: true });
      this.setBackDetail();
    }
  },
  // 同意处理
  async agreeOrder () {
    const res = await Api.approve({
      action: '3',
      applicationId: this.data.order.application_id,
      comments: this.data.message
    }, app.globalData.sessionKey);
    if (res) {
      this.data.agreeDialog.hideModal();
      prompt.showToast('已同意申请', 'success', { mask: true });
      this.setBackApproval();
    }
  },
  // 转交处理
  async deliverOrder () {
    const res = await Api.approve({
      action: '2',
      applicationId: this.data.order.application_id,
      comments: this.data.message,
      forwardUsertel: this.data.originDeliverList[this.data.deliverIndex].usertel
    }, app.globalData.sessionKey);
    if (res) {
      this.data.agreeDialog.hideModal();
      prompt.showToast('转交成功', 'success', { mask: true });
      this.setBackApproval();
    }
  },
  // 拒绝处理
  async refuseOrder () {
    const res = await Api.approve({
      action: '4',
      applicationId: this.data.order.application_id,
      comments: this.data.message
    }, app.globalData.sessionKey);
    if (res) {
      this.data.agreeDialog.hideModal();
      prompt.showToast('已拒绝申请', 'success', { mask: true });
      this.setBackApproval();
    }
  },

  /* --=================功能函数=================-- */
  // 设置撤回操作返回刷新
  setBackDetail () {
    app.globalData.refresh_myOrder = true; // 刷新我的预约列表
    setTimeout(() => {
      wx.navigateBack({
        delta: 1
      });
    }, 2000);
  },
  // 设置审核操作返回刷新
  setBackApproval () {
    app.globalData.refresh_myApproval = true; // 刷新我的预约列表
    setTimeout(() => {
      wx.navigateBack({
        delta: 1
      });
    }, 2000);
  },

  /* --=================事件处理=================-- */
  // 同意按钮点击处理
  handlAgreeBtnTap () {
    const _this = this;
    this.data.agreeDialog.showModal({
      title: '同意申请',
      confrimHide: false,
      async comfirm () {
        const pPrp = await prompt.showModal('确认同意申请吗？', { showCancel: true });
        if (pPrp.confirm) {
          _this.agreeOrder();
        }
      },
      cancel () {
        _this.setData({ message: '' });
      }
    });
  },
  // 转发按钮点击处理
  handledeliverTap () {
    const _this = this;
    this.data.deliverDialog.showModal({
      title: '转发',
      confrimHide: false,
      async comfirm () {
        if (_this.data.deliverIndex < 0) {
          prompt.showToast('请选择转交的审批人');
        } else {
          const pPro = await prompt.showModal('确认转发申请吗？', { showCancel: true });
          if (pPro.confirm) {
            _this.deliverOrder();
          }
        }
      },
      cancel () {
        _this.setData({ message: '' });
      }
    });
  },
  // 拒绝按钮点击处理
  handleRefuseTap () {
    const _this = this;
    this.data.refuseDialog.showModal({
      title: '拒绝申请',
      confrimHide: false,
      async comfirm () {
        const pPro = await prompt.showModal('确认拒绝申请吗？', { showCancel: true });
        if (pPro.confirm) {
          _this.refuseOrder();
        }
      },
      cancel () {
        _this.setData({ message: '' });
      }
    });
  },
  // 转交处理人选择事件
  handleDeliverChange (e) {
    this.setData({ deliverIndex: +e.detail.value });
  },
  // 撤回按钮点击处理
  async handleWithdrawBtnClick () {
    const res = await prompt.showModal('撤回后记录会被删除，若需要请重新申请，确定要撤回申请吗？', {
      showCancel: true
    });
    if (res.confirm) {
      this.revokeOrder();
    }
  },
  // 留言文本input事件处理
  handleTextareaInput (e) {
    const param = {};
    param[e.currentTarget.dataset.state] = e.detail.value;
    this.setData(param);
  }
});